import fs from 'fs';
import http from 'http';
import https from 'https';

import gzipMod from './module/gzip';
import defaultMod from './module/default';

import { IServer } from '../common/serve';
import { getAssetPath, hasSuffix } from './common/util';

function runApp() {
    process?.on?.('message', (serverConfig: IServer) => {
        // ...
        let options = {};
        const httpT = serverConfig.openHttps ? https : http;

        // HTTPS
        if (serverConfig.openHttps) {
            let privateKey = '';
            let certificate = '';
            if (fs.existsSync(serverConfig.privateKey) && fs.existsSync(serverConfig.certificate)) {
                privateKey = fs.readFileSync(serverConfig.privateKey, 'utf-8');
                certificate = fs.readFileSync(serverConfig.certificate, 'utf-8');
            }

            options = { key: privateKey, cert: certificate };
        }

        const app = (httpT as typeof http).createServer(options, (request, response) => {
            let { url, headers } = request;
            url = decodeURI(url || '');

            // 是否压缩
            const isCompress = serverConfig.openGZip && headers['accept-encoding'] && hasSuffix(url);

            let assetsPath = '';
            if (url === '/') {
                assetsPath = getAssetPath(serverConfig.assetsDirPath, serverConfig.defaultAssets);
            } else {
                assetsPath = getAssetPath(serverConfig.assetsDirPath, url);
            }

            if (isCompress) {
                gzipMod(request, response, serverConfig, assetsPath);
            } else {
                defaultMod(request, response, serverConfig, assetsPath);
            }
        });

        app.listen(serverConfig.port, () => {
            process?.send?.('server_is_running');
        });
    });

    process?.send?.('start_server');
}
runApp();
